﻿namespace ApiTemplate.WebApi.Config
{
    /// <summary>
    /// 初始化数据库
    /// </summary>
    public class AppStart : IStartable
    {
        private readonly ICommonDAL _commonDAL;

        private readonly ISchedulerTaskDAL _schedulerTaskDAL;

        private readonly ISchedulerTaskLogDAL _schedulerTaskLogDAL;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="commonDAL"></param>
        /// <param name="schedulerTaskDAL"></param>
        /// <param name="schedulerTaskLogDAL"></param>
        public AppStart(ICommonDAL commonDAL, ISchedulerTaskDAL schedulerTaskDAL, ISchedulerTaskLogDAL schedulerTaskLogDAL)
        {
            _commonDAL = commonDAL;
            _schedulerTaskDAL = schedulerTaskDAL;
            _schedulerTaskLogDAL = schedulerTaskLogDAL;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public void Start()
        {
            AppSetting appSetting = ConfigHelper.GetAppSetting();
            if (appSetting.InitDataTable)
            {
                _commonDAL.InitDataTable();
            }
            if (appSetting.EnableSchedulerTask)
            {
                InitSchedulerTask();
            }
        }

        /// <summary>
        /// 初始化调度任务
        /// </summary>
        /// <returns></returns>
        private void InitSchedulerTask()
        {
            //获取数据库中所有的调度任务
            List<GetSchedulerTaskOutput> list = _schedulerTaskDAL.GetAllSchedulerTaskList();
            foreach (var item in list)
            {
                StdSchedulerFactory factory = new();

                IScheduler _scheduler = factory.GetScheduler().Result;
                //job中需要使用到数据访问层，这里自定义实现
                ExtendJobFactory myJobFactory = new(_schedulerTaskDAL, _schedulerTaskLogDAL);
                _scheduler.JobFactory = myJobFactory;
                _scheduler.Start().Wait();

                //创建job
                IJobDetail job = JobBuilder.Create<HttpJob>()
                        .WithIdentity(new JobKey(item.Id))
                        .Build();

                AddSchedulerTaskInput input = new()
                {
                    CronStr = item.CronStr,
                    Parameter = item.Parameter,
                    RequsetType = item.RequsetType,
                    Url = item.Url,
                    TaskName = item.TaskName
                };
                job.JobDataMap.Add("input", input);//添加参数
                job.JobDataMap.Add("taskId", item.Id);//添加参数

                //立即执行
                ITrigger trigger = TriggerBuilder.Create()
                        .WithIdentity(item.Id)
                        .StartNow()
                        .WithCronSchedule(input.CronStr)
                        .Build();
                _scheduler.ScheduleJob(job, trigger).Wait();
            }
        }
    }
}
